package com.ht.api.call.func.impl.ad;

import java.util.ArrayList;
import java.util.List;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.business.ad.PlanHelper;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * 统计满足人群和条件规则的客户数量
 * @author asq
 * @createTime 2025年3月12日 13:31:46
 */
public class CountCustomerFunctionCall implements IFunctionCall {

	@Override
	public String getName() {
		return "统计满足人群和条件规则的客户数量";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		// 获取参数 
		JSONArray audienceRule = param.getJSONArray("audience_rule");
		JSONObject conditionRule = param.getJSONObject("condition");

		// 查询
		List<Object> paramList = new ArrayList<>();
		String sql = PlanHelper.buildAudienceAndConditionSql(audienceRule, conditionRule, paramList, false);
		sql = "select bitmap_count(cc.oneid) num from (" + sql + ") cc ";
		Long count = Db.val(me.getDataSource(), sql, paramList);

		return JSONUtil.createObj().set("count", count == null ? 0 : count.intValue());
	}

}
